const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const adminRoutes = require('./routes/admin.route');
const errorHandler = require('./utils/errorHandler');

// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();

// 中间件
app.use(helmet());
app.use(cors({
    origin: process.env.CORS_ORIGIN || '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('dev'));

// 日志中间件
const { requestLogger } = require('./utils/logger');
app.use(requestLogger);

// 路由
app.use('/api/admin', adminRoutes);

// 错误处理中间件
app.use(errorHandler);

// 服务器监听
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;